package com.atguigu.tingshu.user.strategy.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.csp.sentinel.command.annotation.CommandMapping;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserVipService;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.user.mapper.VipServiceConfigMapper;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author dxt
 * @create 2025-07-01-16:27
 */
@Component("1003")
public class VipStrategy implements ItemTypeStrategy {

    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserVipServiceMapper userVipServiceMapper;

    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        //获取去购买的月份
        VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(userPaidRecordVo.getItemIdList().get(0));
        Integer serviceMonth = vipServiceConfig.getServiceMonth();
        //获取用户信息
        UserInfo userInfo = userInfoMapper.selectById(userPaidRecordVo.getUserId());
        //新增vip会员购买记录
        UserVipService userVipService = new UserVipService();
        userVipService.setUserId(userPaidRecordVo.getUserId());
        userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
        userVipService.setStartTime(new Date());
        //用户是vip
        if(userInfo.getIsVip() == 1 && new Date().before(userInfo.getVipExpireTime())){
            userVipService.setStartTime(userInfo.getVipExpireTime());
        }
        userVipService.setExpireTime(DateUtil.offsetMonth(userVipService.getStartTime(), serviceMonth));
        userVipServiceMapper.insert(userVipService);
        //更新用户信息
        userInfo.setIsVip(1);
        userInfo.setVipExpireTime(userVipService.getExpireTime());
        userInfoMapper.updateById(userInfo);
    }
}
